'''
@Author: your name
@Date: 2019-06-24 11:32:40
LastEditTime: 2021-04-02 11:57:08
LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /tinyms/tinyms-api/apps/main/login/views.py
'''
#coding=UTF-8
from app import app,auth
from flask import Flask, jsonify,request,g,current_app
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, BadSignature
import json
from . import main_login

# import sys
# sys.path.append("../../../")
from apps.auth.user.model import User
from apps.utils import auty

@main_login.route('/')
def index():
    """欢迎使用点点系统"""
    data = {
        'state': 'success',
        'msg': '欢迎使用本系统'
    }
    return json.dumps(data,ensure_ascii=False)


#用户登录，并产生token
@main_login.route('/login',methods=['GET','POST'])
@auth.verify_password
def login():
    if request.method == "POST":
        username = request.form.get("username") #获取用户名
        password = request.form.get("password") #获取密码
    else:
        username = request.args.get("username") #获取用户名
        password = request.args.get("password") #获取密码
    # 从所有参数中获取对应参数的值    
    # username = request.values.get("username") #获取用户名
    # password = request.values.get("password") #获取密码

    current_app.logger.debug("********")
    current_app.logger.debug(username)
    user = User.query.filter(User.user_loginname==username).first()
    current_app.logger.debug(user)
    current_app.logger.debug("********")
    if not user:
        data = {
            'state':'fail',
            'msg':'登录失败',
        }
        return jsonify({'data':data})
    g.user = user
    #生成token
    token = auty.create_auth_token(g.user.user_pk)
    data = {
        'token':token,
        'state':'success',
        'msg':'登录成功',
        'user':User.obj_dict(user)
    }
    return jsonify({ 'data': data })
    # return jsonify({ 'token': token.decode('ascii') })



@main_login.route('/api/resource')
@auth.login_required
def get_resource():
    return jsonify({ 'data': 'Hello, %s!' % g.user.user_loginname })


@app.route('/api/login')
@auth.login_required
def get_auth_token():
    token = auty.create_auth_token()
    return jsonify(token)